import { invoke } from '@vueuse/shared'
import type { Ref } from 'vue'

export const watchImmediate = (data, callback) => watch(data, callback, { immediate: true })
export const useCounting = () => {
  const COUNT_NUM = 30
  const { count } = useCounter(COUNT_NUM)
  const isCountingFinished = ref(true)
  let timer
  const startCounting = () =>
    invoke(async () => {
      isCountingFinished.value = false
      timer = setInterval(() => count.value--, 1000)
      await until(count).toMatch((v) => v === 0)
      clearInterval(timer)
      count.value = COUNT_NUM
      isCountingFinished.value = true
    })
  onUnmounted(() => clearInterval(timer))
  return { isCountingFinished, count, startCounting }
}

export function useMyStorage(key: string, defaultValue: any): Ref<any> {
  let _serverState = useState(key, () => defaultValue)
  let _clientState = useLocalStorage(key, defaultValue)
  const hasServerData = Object.values(_serverState.value).length
  const hasClientData = Object.values(_clientState.value).length
  if (process.client && hasServerData) _clientState.value = _serverState.value
  return computed({
    get() {
      if (process.server || !hasClientData) return _serverState.value
      return _clientState.value
    },
    set(v) {
      return (_serverState.value = _clientState.value = v)
    },
  })
}

export function memberLogout(refresh?: boolean) {
  localStorage.removeItem('authToken')
  localStorage.removeItem('memberInfo')
  showLoadingToast({ duration: 0, forbidClick: true })
  if (!refresh) {
    return (location.href = '/sso/login')
  }
  location.reload()
}

export function goodsPlayerIdIsInValid(goodsId: number, rechargePlatformConfig: Ref<any[]>) {
  const isHOK = goodsId === 2139 || goodsId === 2457
  if (isHOK) {
    const isNotNumber = isNaN(+rechargePlatformConfig.value?.[0]?.value)
    const isLessThan6 = String(rechargePlatformConfig.value?.[0]?.value).length < 6
    return isNotNumber || isLessThan6
  }
  return false
}
